<template>
  <div class="login-container">
    <div id="particles-js"></div>
    <el-form class="login-form" ref="ruleFormRef" :model="loginForm" :rules="loginRules">
      <div class="title-container">
        <h3 class="title">系统登录</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input placeholder="用户名" name="username" type="text" v-model="loginForm.username" />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input placeholder="密码" name="password" v-model="loginForm.password" :type="passwordType" />
        <span class="show-pwd">
          <span class="svg-container">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" @click="onChangePwdType" />
          </span>
        </span>
      </el-form-item>

      <el-button type="primary" style="width: 100%; margin-bottom: 30px" :loading="loading" size="large"
        @click="handleLogin(ruleFormRef)">登 录</el-button>
    </el-form>
  </div>
</template>

<script setup lang="ts" name="login">
import { validUsername } from "@/utils/validate";
import { useUserStore } from "@/store/user";
import type { FormInstance } from 'element-plus'
import particlesJson from '@/assets/particles/particles.json'

// 数据源
const loginForm = reactive({
  username: 'admin',
  password: '123456'
})

//填写校验
const validateUsername = (rule: any, value: any, callback: any) => {
  if (!validUsername(value)) {
    callback(new Error("请输入正确的用户名！"));
  } else {
    callback();
  }
};

const validatePassword = (rule: any, value: any, callback: any) => {
  if (value.length < 6) {
    callback(new Error("密码不能少于6位数！"));
  } else {
    callback();
  }
};

// 验证规则
const loginRules = reactive({
  username: [{ required: true, trigger: "blur", validator: validateUsername }],
  password: [{ required: true, trigger: "blur", validator: validatePassword }],
});

// 处理密码框文本显示状态
const passwordType = ref('password')
const onChangePwdType = () => {
  if (passwordType.value === 'password') {
    passwordType.value = 'text'
  } else {
    passwordType.value = 'password'
  }
}

// 登录动作处理
const loading = ref(false)
const ruleFormRef = ref<FormInstance>()
const handleLogin = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!')
      loginReq()
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const state = reactive({
  otherQuery: {},
  redirect: ''
})

const router = useRouter();
const route = useRoute();

const getOtherQuery = (query: any) => {
  return Object.keys(query).reduce((acc: any, cur) => {
    if (cur !== 'redirect') {
      acc[cur] = query[cur]
    }
    return acc
  }, {})
}

watch(
  () => route.query,
  (query) => {
    if (query) {
      state.redirect = (query.redirect) as string
      state.otherQuery = getOtherQuery(query)
    }
  },
  { immediate: true }
)

const loginReq = () => {
  loading.value = true;
  const userStore = useUserStore();
  userStore.login(loginForm).then(() => {
    router.push({ path: state.redirect || '/', query: state.otherQuery })
    setTimeout(() => {
      loading.value = false;
    }, 600)
  }).catch((err) => {
    console.log(err);
    loading.value = false;
  });
}

onMounted(() => {
  //知乎粒子效果
  window.particlesJS('particles-js', particlesJson);
})

onUnmounted(() => {
  window.pJSDom[0].pJS.fn.vendors.destroypJS();
  window["pJSDom"] = [];
})
</script>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
$cursor: #fff;

.login-container {
  height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: absolute;
    top: -20%;
    left: 0;
    right: 0;
    bottom: 0;
    width: 520px;
    height: 500px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: auto;
    overflow: hidden;

    :deep(.el-input__wrapper) {
      display: block;
      box-shadow: none !important;
    }

    :deep(.el-form-item) {
      border: 1px solid #273444;
      background: #273444;
      border-radius: 5px;
      color: #454545;
      box-shadow: none !important;
      margin-bottom: 28px;
    }

    :deep(.el-input) {
      display: inline-block;
      height: 47px;
      width: 85%;
      --el-input-focus-border-color: none;
      --el-input-border-color: none;
      --el-input-hover-border-color: none;

      .el-input__wrapper {
        background: transparent;
      }

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;
      }
    }
  }

  .tips {
    font-size: 16px;
    color: white;
    line-height: 24px;
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>